<template>
<div class="auth-container">
  <el-card class="auth-card">
    <transition name="fade" mode="out-in">
      <div v-if="isLogin" key="login">
        <h3>CCR宠物商城</h3>
        <h2 class="auth-title">{{ isLogin ? '欢迎登录' : '用户注册' }}</h2>
        <el-tabs v-model="loginType" stretch @tab-click="clearForms('login')">
          <el-tab-pane label="账号登录" name="account">
            <el-form
              :model="loginForm"
              :rules="loginRules"
              ref="loginFormRef"
              label-width="80px">
              <el-form-item label="账号" prop="user.username">
                <el-input v-model="loginForm.user.username" placeholder="用户名/手机号"/>
              </el-form-item>
              <el-form-item label="密码" prop="user.password">
                <el-input v-model="loginForm.user.password" show-password placeholder="请输入密码"/>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="手机登录" name="phone">
            <el-form
              :model="loginForm"
              :rules="phoneLoginRules"
              ref="phoneLoginFormRef"
              label-width="80px">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="loginForm.user.phone" placeholder="请输入手机号"/>
              </el-form-item>
              <el-form-item label="验证码" prop="code">
                <div class="code-input">
                  <el-input v-model="loginForm.code" placeholder="6位验证码"/>
                  <el-button
                    type="primary"
                    :disabled="countdown > 0"
                    @click="sendcode">
                    {{ countdown ? `${countdown}秒后重发` : '获取验证码' }}
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <div class="action-area">
          <el-button
            type="primary"
            class="submit-btn"
            @click="handleLogin">
            {{ loginType === 'account' ? '立即登录' : '验证登录' }}
          </el-button>
          <div class="switch-action">
            <span @click="toggleAuth">立即注册</span>
          </div>
        </div>
      </div>

      <div v-else key="register">
        <h2 class="auth-title">用户注册</h2>
        <el-form
          :model="registerForm"
          :rules="registerRules"
          ref="registerFormRef"
          label-width="100px">
          <el-form-item label="手机号" prop="user.phone">
            <el-input v-model="registerForm.user.phone" placeholder="请输入手机号"/>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <div class="code-input">
              <el-input v-model="registerForm.code" placeholder="6位验证码"/>
              <el-button
                type="primary"
                :disabled="countdown > 0"
                @click="sendcode">
                {{ countdown ? `${countdown}秒后重发` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="设置密码" prop="user.password">
            <el-input v-model="registerForm.user.password" show-password placeholder="8-20位字母数字组合"/>
          </el-form-item>
          <el-form-item label="确认密码" prop="user.confirmPassword">
            <el-input v-model="registerForm.user.confirmPassword" show-password placeholder="请再次输入密码"/>
          </el-form-item>
        </el-form>
        <div class="action-area">
          <el-button
            type="primary"
            class="submit-btn"
            @click="handleRegister">
            立即注册
          </el-button>
          <div class="switch-action">
            已有账号？<span @click="toggleAuth">立即登录</span>
          </div>
        </div>
      </div>
    </transition>
  </el-card>
</div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useUserStore } from "@/stores/user";
import {sendSms, register, loginByPhone, login} from "@/common/net/api";

const userStore = useUserStore();

// 表单类型
type LoginType = 'account' | 'phone';

// 状态管理
const isLogin = ref(true);
const loginType = ref<LoginType>('account');
const countdown = ref(0);
let timer: number;

// 登录表单
const loginForm = reactive({
  user: {
    username: '',
    password: '',
    phone: '',
  },
  code: ''
});

// 注册表单
const registerForm = reactive({
  user: {
    phone: '',
    password: '',
  },
  code: '',
  confirmPassword: ''
});

// 表单引用
const loginFormRef = ref<FormInstance>();
const phoneLoginFormRef = ref<FormInstance>();
const registerFormRef = ref<FormInstance>();

// 验证规则
const validatePassword = (rule: any, value: string, callback: Function) => {
  if (!/(?=.*[a-zA-Z])(?=.*\d).{8,20}/.test(value)) {
    callback(new Error('需包含字母和数字，长度8-20位'));
  } else {
    callback();
  }
};

const loginRules: FormRules = {
  'user.username': [{ required: true, message: '请输入账号', trigger: 'blur' }],
  'user.password': [{ required: true, message: '请输入密码', trigger: 'blur' }]
};

const phoneLoginRules: FormRules = {
  'user.phone': [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码格式不正确' }
  ]
};

const registerRules: FormRules = {
  'user.phone': phoneLoginRules['user.phone'],
  code: phoneLoginRules.code,
  'user.password': [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (value !== registerForm.user.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 发送验证码
const sendcode = async () => {
  const phone = isLogin.value ? loginForm.user.phone : registerForm.user.phone;
  console.log(phone)
  const result = await sendSms(phone);
  if (result.data.state) {
    startCountdown();
    ElMessage.success("发送成功");
  } else {
    ElMessage.error(result.data.msg);
  }
};

// 倒计时处理
const startCountdown = () => {
  countdown.value = 60;
  timer = window.setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};

// 切换登录/注册
const toggleAuth = () => {
  isLogin.value = !isLogin.value;
  clearForms();
};

// 清空表单
const clearForms = () => {
  loginFormRef.value?.resetFields();
  phoneLoginFormRef.value?.resetFields();
  registerFormRef.value?.resetFields();
};

// 登录处理
const handleLogin = async () => {
  const formRef = loginType.value === 'account' ? loginFormRef.value : phoneLoginFormRef.value;
  if (!formRef) return;

  formRef.validate(async (valid) => {
    if (valid) {
      if (loginType.value === 'account') {
        // 账号密码登录逻辑
        await userStore.handleLogin(loginForm.user);
      } else {
        // 手机验证码登录逻辑
        await userStore.handleLoginByPhone(loginForm)
      }
    } else {
      ElMessage.error('表单校验失败，请检查输入');
    }
  });
};

// 注册处理
const handleRegister = async () => {
  registerFormRef.value?.validate(async (valid) => {
    let registerData = {
      user:{
        phone: registerForm.user.phone,
        password: registerForm.user.password,
      },
      code: registerForm.code,
    }
    console.log(registerData);
    if (valid) {
      const result = await register(registerData);
      if (result.data.state) {
        ElMessage.success("注册成功,请登录！");
        toggleAuth();
      } else {
        ElMessage.error(result.data.msg);
      }
    } else {
      ElMessage.error('表单校验失败，请检查输入');
    }
  });
};
</script>

<style scoped>
.auth-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.5s ease; /* 添加背景颜色过渡效果 */
  background-color: #42b983; /* 初始背景颜色 */
}

.auth-card {
  width: 420px;
  padding: 30px;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.auth-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, #42b983, #64d8b5, #86f2e7);
  opacity: 0.5;
  transition: opacity 0.5s ease; /* 添加渐变透明度过渡效果 */
  z-index: -1;
}

.auth-card:hover::before {
  opacity: 0.7; /* 鼠标悬停时增强渐变效果 */
}

.code-input {
  display: flex;
  gap: 10px;
}

.action-area {
  margin-top: 30px;
  text-align: center;
}

.submit-btn {
  width: 100%;
  height: 40px;
  margin-bottom: 15px;
  border-radius: 20px;
}

.switch-action {
  color: #666;
  font-size: 14px;
  cursor: pointer;
}

.switch-action span {
  color: #409eff;
  margin: 0 5px;
}

.switch-action span:hover {
  text-decoration: underline;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
</style>
